import httplib2
import urllib
import encode
import urllib2

http = httplib2.Http()

def get_cookie() :
  login_url = "http://graphics.sci.ubu.ac.th/login/index.php"

  login_params = urllib.urlencode({
	  'username' : 'beer',
	  'password' : "linuxadmin",
	  'testcookies' : '1'
	  })	 
  headers = {'Content-type': 'application/x-www-form-urlencoded'} 
  response, content = http.request(login_url, method='POST', body=login_params, headers=headers)
  
  return response['set-cookie']

def gen_request_params(moodle_cookie, subject = 'test' , message = 'just test from python'):
  #find MoodleSessionTest value
  
  import Cookie
  cookie = Cookie.SimpleCookie()
  cookie.load(moodle_cookie)
  
  moodle_session_test = cookie['MoodleSessionTest'].value
  
  fields = {
    "MAX_FILE_SIZE": "1048576",
    "timestart": "0" ,
    "timeend": "0" ,
    "course": "1" ,
    "forum": "112" ,
    "discussion": "0" ,
    "parent": "0" ,
    "userid": "235" ,
    "groupid": "" ,
    "edit": "0" ,
    "reply": "0" ,
    "sesskey": moodle_session_test ,
    "_qf__mod_forum_post_form": "1" ,
    "message" : message,
    "subject" : subject,
    "submitbotton" : "Post to  Forum"
  }
  
  content_type, body = encode.encode_multipart_formdata(fields.iteritems(), {}.iteritems())
  
  return content_type, body

def post(url, method, body, header):
  response, content = http.request(url, method= method, body = body, headers=header)
  return response, content

url = 'http://graphics.sci.ubu.ac.th/mod/forum/post.php'

moodle_cookie = get_cookie()
content_type, body = gen_request_params(moodle_cookie)

print content_type 
print '-------------------------------------'
print body


import cookielib

cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
urllib2.install_opener(opener)


headers = {'Content-Type': content_type,'Content-Length': str(len(body))}
headers['Cookie'] = moodle_cookie


#r = urllib2.Request("http://%s%s" % (host, selector), body, headers)
r = urllib2.Request(url, body, headers)
urllib2.urlopen(r).read()





	  